package com.txw.travel.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.txw.travel.bean.PermissionWithStatus;
import com.txw.travel.mapper.PermissionMapper;
import com.txw.travel.mapper.RoleMapper;
import com.txw.travel.pojo.Permission;
import com.txw.travel.pojo.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional//add tran
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    public Role getRoleById(Integer rid) {
        return roleMapper.selectById(rid);
    }

    public Page<Role> getRoleList(Integer index, Integer size) {
        return roleMapper.selectPage(new Page<Role>(index, size), null);
    }

    public void insertRole(Role role) {
        roleMapper.insert(role);
    }

    public void updateRole(Role role) {
        roleMapper.updateById(role);
    }

    public void deleteRoleById(Integer rid) {
        roleMapper.deleteById(rid);
    }

    public List<PermissionWithStatus> getPermissionWithStatus(Integer rid) {
        List<PermissionWithStatus> roleWithPermissions = new ArrayList<>();
        List<Permission> permissions = permissionMapper.selectList(null);
        List<Integer> rolePermissionIds = permissionMapper.getPermissionIdByRoleId(rid);

        for (Permission permission : permissions) {
            PermissionWithStatus roleWithPermission = new PermissionWithStatus();
            BeanUtils.copyProperties(permission, roleWithPermission);
            roleWithPermission.setHasPermission(rolePermissionIds.contains(permission.getPid()));
            roleWithPermissions.add(roleWithPermission);
        }

        return roleWithPermissions;
    }

    public void updateRolePermission(Integer rid, Integer[] pids) {
        roleMapper.deleteRolePermissionByRoleId(rid);

        if (pids == null)
            return;

        for (Integer pid : pids) {
            roleMapper.addRolePermission(rid, pid);
        }
    }
}
